package com.zihan.inteceptor;


import com.zihan.constant.JwtClaimsConstant;
import com.zihan.context.UserContext;
import com.zihan.domain.entity.User;
import com.zihan.properties.JwtProperties;
import com.zihan.utils.JwtUtil;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        log.debug("Request URI: {}", request.getRequestURI());
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取token信息
        String token = request.getHeader("authorization");
        if (token == null || token.trim().isEmpty()) {
            response.setStatus(401);
            return false;
        }
        // 解析token
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long userId = Long.parseLong(claims.get(JwtClaimsConstant.USER_ID).toString());
            UserContext.setCurrentId(userId);
            return true;
        }catch (ExpiredJwtException e) {
            // Token 已过期
            response.setStatus(402);
            return false;
        } catch (MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
            response.setStatus(401);
            return false;
        }
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeCurrentId();
    }
}
